package com.ocean.admin.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ocean.admin.entity.SysRole;
import com.ocean.admin.entity.SysUser;
import com.ocean.admin.entity.SysUserPost;
import com.ocean.admin.entity.SysUserRole;
import com.ocean.admin.extension.ConstantsCacheExtension;
import com.ocean.admin.extension.security.core.SysUserDetails;
import com.ocean.admin.extension.security.filter.WebFilterExtend;
import com.ocean.admin.mapper.SysUserMapper;
import com.ocean.admin.model.dto.user.SysUserQueryDTO;
import com.ocean.admin.model.dto.user.SysUserSaveDTO;
import com.ocean.admin.model.dto.user.SysUserUpdateDTO;
import com.ocean.admin.model.dto.user.SysUserUpdatePasswordDTO;
import com.ocean.admin.model.vo.menu.SysMenuVo;
import com.ocean.admin.model.vo.router.MetaVo;
import com.ocean.admin.model.vo.router.RouterVo;
import com.ocean.admin.model.vo.user.SysUserInfoVo;
import com.ocean.admin.model.vo.user.SysUserVo;
import com.ocean.admin.service.*;
import com.ocean.core.exception.verify.ApplicationException;
import com.ocean.core.util.StringUtil;
import com.ocean.core.util.constants.ConstantsAttribute;
import com.ocean.core.util.constants.ConstantsOther;
import com.ocean.security.properties.SuperAdminProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author zhang
 * @since 2022-08-16
 */
@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private ISysMenuService iSysMenuService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private ISysDictDataService iSysDictDataService;

    @Autowired
    private ISysUserPostService iSysUserPostService;

    @Autowired
    private ISysUserRoleService iSysUserRoleService;

    @Autowired
    private ISysPostService iSysPostService;

    @Autowired
    private ISysRoleService iSysRoleService;

    @Autowired
    private SuperAdminProperties adminProperties;

    /**
     * 认证
     *
     * @param username 用户名
     * @return 用户信息
     */
    @Override
    public SysUserDetails selectUserByUsername(String username) {
        return baseMapper.selectUserByUsername(username);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @Override
    public List<RouterVo> getRouters() {
        List<SysMenuVo> menuList = iSysMenuService.listTree(null);
        return buildRouterMenu(menuList);
    }

    /**
     * 新增用户
     *
     * @param saveDTO 用户信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String saveUser(SysUserSaveDTO saveDTO) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(saveDTO, user);
        this.checkSaveUser(saveDTO);
        SysUserDetails current = WebFilterExtend.current();
        //为空并且不是管理员
        user.setUserId(IdWorker.getId());
        user.setCreateUserId(current.getUserId());
        user.setCreateUserName(current.getNickName());
        user.setUpdateUserId(current.getUserId());
        user.setUpdateUserName(current.getNickName());
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        this.save(user);
        //新增用户岗位关联
        iSysUserPostService.saveUserPost(saveDTO.getPostIds(), user.getUserId());
        //新增用户和角色关系
        iSysUserRoleService.saveUserRole(saveDTO.getRoleIds(), user.getUserId());
        return ConstantsAttribute.INSERT_SUCCESS;
    }

    /**
     * 删除用户
     *
     * @param userIds 用户ID
     * @return 结果
     */
    @Override
    public String removeUser(Long[] userIds) {
        List<Long> idList = Arrays.asList(userIds);
        if (idList.contains(WebFilterExtend.getUserId())) {
            throw new ApplicationException("不能删除当前用户");
        }
        this.removeByIds(idList);
        return ConstantsAttribute.REMOVE_SUCCESS;
    }

    /**
     * 修改用户
     *
     * @param updateDTO 用户信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String updateUser(SysUserUpdateDTO updateDTO) {
        this.checkUpdateUser(updateDTO);
        SysUser user = new SysUser();
        BeanUtils.copyProperties(updateDTO, user);
        SysUserDetails current = WebFilterExtend.current();
        user.setUpdateUserId(current.getUserId());
        user.setUpdateUserName(current.getNickName());
        this.updateById(user);
        //删除用户与角色关联
        iSysUserRoleService.remove(Wrappers.<SysUserRole>lambdaQuery()
                .eq(SysUserRole::getUserId, updateDTO.getUserId()));
        //删除用户和岗位关联
        iSysUserPostService.remove(Wrappers.<SysUserPost>lambdaQuery()
                .eq(SysUserPost::getUserId, updateDTO.getUserId()));
        //新增用户岗位关联
        iSysUserPostService.saveUserPost(updateDTO.getPostIds(), user.getUserId());
        //新增用户和角色关系
        iSysUserRoleService.saveUserRole(updateDTO.getRoleIds(), user.getUserId());
        return ConstantsAttribute.UPDATE_SUCCESS;
    }

    /**
     * 分页查询用户
     *
     * @param queryDTO 查询条件
     * @return 结果
     */
    @Override
    public IPage<SysUserVo> pageList(SysUserQueryDTO queryDTO) {
        Page<SysUserVo> page = new Page<>(queryDTO.getPage(), queryDTO.getPageSize());
        IPage<SysUserVo> list = baseMapper.pageList(page, queryDTO);
        list.getRecords().forEach(res -> {
            res.setUserTypeName(res.getUserType() == 0 ? "系统用户" : "");
            res.setStatusName(res.getStatus() == 1 ? "停用" : "正常");
            res.setSexName(iSysDictDataService.get(ConstantsCacheExtension.getInstance().getSysSex(), res.getSex()));
        });
        return list;
    }

    /**
     * 重置密码
     *
     * @param passwordDTO 密码信息
     * @return 结果
     */
    @Override
    public String resetPassword(SysUserUpdatePasswordDTO passwordDTO) {
        String newPassword = passwordEncoder.encode(passwordDTO.getNewPassword());
        baseMapper.update(null, Wrappers.<SysUser>lambdaUpdate()
                .eq(SysUser::getUserId, passwordDTO.getUserId()).set(SysUser::getPassword, newPassword));
        return ConstantsAttribute.RESET_SUCCESS;
    }

    /**
     * 查询用户详情
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public SysUserInfoVo queryInfo(Long userId) {
        SysUserInfoVo userInfoVo = new SysUserInfoVo();
        SysUser sysUser = baseMapper.selectById(userId);
        userInfoVo.setUser(sysUser);
        userInfoVo.setPostIds(baseMapper.selectPost(userId));
        userInfoVo.setRoleIds(baseMapper.selectRole(userId));
        //可选择的下拉框
        userInfoVo.setPostList(iSysPostService.list());
        if (WebFilterExtend.hasAdmin()) {
            userInfoVo.setRoleList(iSysRoleService.list());
        } else {
            userInfoVo.setRoleList(iSysRoleService.list(Wrappers.<SysRole>lambdaQuery()));
        }
        return userInfoVo;
    }

    /**
     * 修改用户状态
     *
     * @param userId 用户ID
     * @param status 帐号状态（0正常 1停用）
     * @return 结果
     */
    @Override
    public String updateStatus(Long userId, Integer status) {
        this.update(null, Wrappers.<SysUser>lambdaUpdate().set(SysUser::getStatus, status)
                .eq(SysUser::getUserId, userId));
        return ConstantsAttribute.UPDATE_SUCCESS;
    }

    private void checkUpdateUser(SysUserUpdateDTO updateDTO) {
        Set<String> userRoles = iSysRoleService.selectRolesByUserId(updateDTO.getUserId());
        if (userRoles.contains(adminProperties.getKey())) {
            throw new ApplicationException("不允许操作管理员用户");
        }
        if (StringUtil.isNotNull(updateDTO.getPhoneNumber())) {
            SysUser phoneUser = baseMapper.selectOne(Wrappers.<SysUser>lambdaQuery()
                    .eq(SysUser::getPhoneNumber, updateDTO.getPhoneNumber()));
            if (phoneUser != null && !Objects.equals(phoneUser.getUserId(), updateDTO.getUserId())) {
                throw new ApplicationException("手机号已存在，请更换");
            }
        }
        if (StringUtil.isNotNull(updateDTO.getEmail())) {
            SysUser emailUser = baseMapper.selectOne(Wrappers.<SysUser>lambdaQuery()
                    .eq(SysUser::getEmail, updateDTO.getEmail()));
            if (emailUser != null && !Objects.equals(emailUser.getUserId(), updateDTO.getUserId())) {
                throw new ApplicationException("邮箱已存在，请更换");
            }
        }
    }

    private void checkSaveUser(SysUserSaveDTO saveDTO) {
        Long usernameCount = baseMapper.selectCount(Wrappers.<SysUser>lambdaQuery()
                .eq(SysUser::getUserName, saveDTO.getUserName()));
        if (usernameCount > 0) {
            throw new ApplicationException("用户名已存在，请更换");
        }
        if (saveDTO.getPhoneNumber() != null) {
            Long phoneCount = baseMapper.selectCount(Wrappers.<SysUser>lambdaQuery()
                    .eq(SysUser::getPhoneNumber, saveDTO.getPhoneNumber()));
            if (phoneCount > 0) {
                throw new ApplicationException("手机号已存在，请更换");
            }
        }
        if (saveDTO.getEmail() != null) {
            Long emailCount = baseMapper.selectCount(Wrappers.<SysUser>lambdaQuery()
                    .eq(SysUser::getEmail, saveDTO.getEmail()));
            if (emailCount > 0) {
                throw new ApplicationException("邮箱已存在，请更换");
            }
        }
    }

    /**
     * 构建路由结构
     *
     * @param menuList 菜单List
     * @return 路由结构
     */
    private List<RouterVo> buildRouterMenu(List<SysMenuVo> menuList) {
        List<RouterVo> routers = new LinkedList<>();
        for (SysMenuVo menu : menuList) {
            RouterVo router = new RouterVo();
            router.setHidden(1 == menu.getVisible());
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), Objects.equals(1, menu.getIsCache()),
                    menu.getPath()));
            List<SysMenuVo> cMenus = menu.getChildren();
            if (!cMenus.isEmpty() && ConstantsOther.TYPE_DIR.equals(menu.getMenuType())) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildRouterMenu(cMenus));
            } else if (isMenuFrame(menu)) {
                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), Objects.equals(1, menu.getIsCache()),
                        menu.getPath()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            } else if (menu.getParentId().intValue() == 0 && isInnerLink(menu)) {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                router.setPath("/");
                List<RouterVo> childrenList = new ArrayList<>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(ConstantsOther.INNER_LINK);
                children.setName(StringUtils.capitalize(routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysMenuVo menu) {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(SysMenuVo menu) {
        return menu.getParentId().intValue() == 0 && ConstantsOther.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(ConstantsOther.NO_FRAME);
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(SysMenuVo menu) {
        return menu.getIsFrame().equals(ConstantsOther.NO_FRAME) && StringUtil.isHttp(menu.getPath());
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenuVo menu) {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && ConstantsOther.TYPE_DIR.equals(menu.getMenuType())
                && ConstantsOther.NO_FRAME.equals(menu.getIsFrame())) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 内链域名特殊字符替换
     *
     * @return 替换后的字符
     */
    public String innerLinkReplaceEach(String path) {
        return StringUtils.replaceEach(path, new String[]{ConstantsOther.HTTP, ConstantsOther.HTTPS},
                new String[]{"", ""});
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenuVo menu) {
        String component = ConstantsOther.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu)) {
            component = menu.getComponent();
        } else if (StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            component = ConstantsOther.INNER_LINK;
        } else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu)) {
            component = ConstantsOther.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(SysMenuVo menu) {
        return menu.getParentId().intValue() != 0 && ConstantsOther.TYPE_DIR.equals(menu.getMenuType());
    }
}
